#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (C) 2025 Huawei Technologies Co., Ltd. All rights reserved.

from ansible.module_utils.basic import AnsibleModule

from openubmc_ansible.openubmc_redfish_api.redfish_base import BmcBaseConnect
from openubmc_ansible.openubmc_redfish_api.api_manage_openubmc_ip import set_bmc_ip
from openubmc_ansible.openubmc_logger import report
from openubmc_ansible.openubmc_logger import log
from openubmc_ansible.utils import is_support_server
from openubmc_ansible.utils import ansible_bmc_run_module
from openubmc_ansible.utils import MSG_FORMAT
from openubmc_ansible.utils import SERVERTYPE


ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = """
---
module: openubmc_set_ip

short_description: Set openubmc ip info

version_added: "2.5.0"

description:
    - "Modify openUBMC network port information"

options:
  openubmc_ip:
    required: true
    default: None
    description:
      - openUBMC IP address
  openubmc_user:
    required: true
    default: None
    description:
      - openUBMC user name used for authentication
  openubmc_pswd:
    required: true
    default: None
    description:
      - openUBMC user password used for authentication
  ip_version:
    required: false
    default: None
    choices: [IPv4, IPv6, IPv4AndIPv6]
    description:
      - Whether IPv4/IPv6 is enabled
  ipv4_addr:
    required: false
    default: None
    description:
      - IPv4 address information of the openUBMC network port
  ipv4_addr/address:
    required: false
    default: None
    description:
      - IPv4 address
  ipv4_addr/subnet_mask:
    required: false
    default: None
    description:
      - Subnet mask of the IPv4 address
  ipv4_addr/gateway:
    required: false
    default: None
    description:
      - Gateway of the IPv4 address
  ipv4_addr/address_origin:
    required: false
    default: None
    choices: [Static, DHCP]
    description:
      - How the IPv4 address is allocated
  ipv6_addr:
    required: false
    default: None
    description:
      - IPv6 address information of the openUBMC network port
  ipv6_addr/address:
    required: false
    default: None
    description:
      - IPv6 address
  ipv6_addr/prefix_length:
    required: false
    default: None
    description:
      - "Prefix length of the IPv6 address, must be an integer, Available Value range: 0 to 128"
  ipv6_addr/address_origin:
    required: false
    default: None
    choices: [Static, DHCPv6]
    description:
      - How the IPv6 address is allocated
  ipv6_gateway:
    required: false
    default: None
    description:
      - IPv6 gateway address of the openUBMC network port
"""

EXAMPLES = """
 - name:  set openubmc ip
    openubmc_set_ip:
      openubmc_ip: "{{ openubmc_ip }}"
      openubmc_user: "{{ openubmc_user }}"
      openubmc_pswd: "{{ openubmc_pswd }}"
      ip_version: "IPv4AndIPv6"
      ipv4_addr:
        - address: "192.168.2.10"
          subnet_mask: "255.255.0.0"
          gateway: "192.168.0.1"
          address_origin: "Static"
      ipv6_addr:
        - address: "fc00:192::10"
          prefix_length: 7
          address_origin: "Static"
      ipv6_gateway: "fc00:192::1"
"""

RETURNS = """
    {"result": True, "msg": "Set openUBMC ethernet interface info successful!"}
"""


def openubmc_set_ip_module(module):
    """
    Function:
        Set openUBMC ethernet interface configuration
    Args:
              module       (class):

    Returns:
        {"result": False, "msg": 'not run set openubmc ip yet'}
    Raises:
        None
    Examples:

    Author:
    Date: 2019/11/4 17:33
    """
    # Modifying the IP address will result in the inability to delete the original session
    # Cannot create an object with the 'with as' method
    openubmc = BmcBaseConnect(module.params, log, report)
    ret = is_support_server(openubmc, SERVERTYPE)
    if ret['result']:
        ret = set_bmc_ip(openubmc, module.params)
        try:
            _ = openubmc.delete_session()
            openubmc.session.close()
        except Exception as e:
            log.info(MSG_FORMAT % (str(openubmc.ip), "Failed to close session, The error info is: %s" % str(e)))
    return ret


def main():
    # Use AnsibleModule to read yml files and convert it to dict
    module = AnsibleModule(
        argument_spec={
            "openubmc_ip": {"required": True, "type": 'str'},
            "openubmc_user": {"required": True, "type": 'str'},
            "openubmc_pswd": {"required": True, "type": 'str', "no_log": True},
            "ip_version": {"required": False, "type": 'str'},
            "ipv4_addr": {"required": False, "type": 'list'},
            "ipv6_addr": {"required": False, "type": 'list'},
            "ipv6_gateway": {"required": False, "type": 'str'}
        },
        supports_check_mode=False)

    ansible_bmc_run_module(openubmc_set_ip_module, module, log, report)


if __name__ == '__main__':
    main()
